import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoginService } from "./login.service";
import { Router } from "@angular/router"

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    validateForm: FormGroup;
    constructor(
        private fb: FormBuilder,
        private loginService : LoginService,
        private router : Router
    ) { }

    ngOnInit() {
        this.validateForm = this.fb.group({
            userName: [null, [Validators.required]],
            password: [null, [Validators.required]],
        });
    }

    submitForm(){
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if( this.validateForm.status == "VALID" ){
            this.loginService.login(this.validateForm.value).subscribe(res=>{
                localStorage.setItem("token", res.token);
                localStorage.setItem("userInfo", JSON.stringify(res.user));
                this.router.navigate(['home']);
            });
        }
    }
}
